<template>
  <div>
    <content-box
      one="用户管理"
      two="用户列表"
    >
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >

            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button
            type="primary"
            @click="addUserDialogVisible = true"
          >添加用户</el-button>
        </el-col>
      </el-row>

      <!-- table区域 -->

      <el-table
        :data="userList"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column type="index"></el-table-column>
        <el-table-column
          label="姓名"
          prop="username"
        ></el-table-column>
        <el-table-column
          label="邮箱"
          prop="email"
        ></el-table-column>
        <el-table-column
          label="电话"
          prop="mobile"
        ></el-table-column>
        <el-table-column
          label="角色"
          prop="role_name"
        ></el-table-column>
        <el-table-column label="状态">
          <!-- 通过作用域插槽渲染用户状态 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="openEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="openSetRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </content-box>

    <!-- 新增用户弹窗 -->
    <el-dialog
      title="新增用户"
      :visible.sync="addUserDialogVisible"
      width="50%"
      @closed="$refs.addFormRef.resetFields()"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="70px"
        :rules="addFormRules"
      >
        <el-form-item
          prop="username"
          label="用户名"
        >
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item
          prop="password"
          label="密码"
        >
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item
          prop="email"
          label="邮箱"
        >
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item
          prop="mobile"
          label="手机"
        >
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addUser"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户弹窗 -->
    <el-dialog
      title="新增用户"
      :visible.sync="editUserDialogVisible"
      width="50%"
      @closed="$refs.editFormRef.resetFields()"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        label-width="70px"
        :rules="editFormRules"
      >
        <el-form-item
          prop="username"
          label="用户名"
        >
          <el-input
            disabled
            v-model="editForm.username"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="email"
          label="邮箱"
        >
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item
          prop="mobile"
          label="手机"
        >
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editUserDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="editUser"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="setRolesDialogVisible"
      width="50%"
    >
      <div>
        <p>当前用户名：{{ userInfo.username }}</p>
        <p>当前角色名：{{ userInfo.role_name }}</p>
        <el-select
          v-model="selectRolesId"
          placeholder="请选择"
        >
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >

          </el-option>
        </el-select>
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="setRolesDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="setRoles"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 定义校验规则
    // 校验邮箱
    var checkEmail = (rule, value, cb) => {
      const testEmail = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      if (!testEmail.test(value)) {
        return cb(new Error("请输入正确的邮箱地址"));
      }
      return cb();
    };
    // 校验电话
    var checkMoblie = (rule, value, cb) => {
      const testMoblie = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-7|9])|(?:5[0-3|5-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1|8|9]))\d{8}$/;
      if (!testMoblie.test(value)) {
        return cb(new Error("请输入正确的手机号"));
      }
      return cb();
    };

    return {
      queryInfo: {
        query: "",
        pagesize: 2,
        pagenum: 1
      },
      total: 0,
      userList: [],
      addUserDialogVisible: false,
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: checkEmail,
            trigger: "blur"
          }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: checkMoblie,
            trigger: "blur"
          }
        ]
      },
      editUserDialogVisible: false,
      editForm: {},
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: checkEmail,
            trigger: "blur"
          }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: checkMoblie,
            trigger: "blur"
          }
        ]
      },
      setRolesDialogVisible: false,
      userInfo: {},
      selectRolesId: "",
      rolesList: []
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });
      if (res.meta.status !== 200) return this.$message.error("获取数据失败");
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    handleSizeChange(val) {
      this.queryInfo.pagesize = val;
      // 重新获取数据
      this.getUserList();
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val;
      this.getUserList();
    },
    async userStateChange(user) {
      const { data: res } = await this.$http.put(
        `users/${user.id}/state/${user.mg_state}`
      );
      if (res.meta.status !== 200) {
        // 还原选中状态
        user.mg_state = !user.mg_state;
        return this.$message.error("修改状态失败");
      }
      this.$message.success("修改状态成功");
    },
    // 添加用户
    addUser() {
      // 表单预校验
      this.$refs.addFormRef.validate(async vali => {
        if (!vali) return;
        // 发起新增请求
        const { data: res } = await this.$http.post("users", this.addForm);
        if (res.meta.status != 201) return this.$message.error("新增失败");
        this.$message.success("添加成功");
        // 重新渲染列表
        this.getUserList();
        // 关闭弹窗
        this.addUserDialogVisible = false;
      });
    },
    // 打开编辑弹窗函数
    async openEditDialog(id) {
      const { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status !== 200)
        return this.$message.error("获取用户信息失败");
      this.editForm = res.data;
      this.editUserDialogVisible = true;
    },
    editUser() {
      // 预校验
      this.$refs.editFormRef.validate(async vali => {
        if (!vali) return;
        const { data: res } = await this.$http.put(
          "users/" + this.editForm.id,
          this.editForm
        );
        if (res.meta.status !== 200) return this.$message.error("修改失败");
        this.$message.success("编辑成功");
        this.getUserList();
        this.editUserDialogVisible = false;
      });
    },
    async deleteUser(id) {
      // 展示弹窗
      const confirmResult = await this.$confirm(
        "此操作将永久删除该数据, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (confirmResult !== "confirm") return this.$message.info("已取消删除");
      // 发起删除请求
      const { data: res } = await this.$http.delete("users/" + id);
      if (res.meta.status !== 200) return this.$message.error("删除失败");
      this.$message.success("删除成功");
      if (this.userList.length == 1 && this.queryInfo.pagenum > 1) {
        this.queryInfo.pagenum -= 1;
      }
      this.getUserList();
    },
    async openSetRoles(userInfo) {
      this.userInfo = userInfo;
      // 获取所有的角色
      const { data: res } = await this.$http.get("roles");
      this.rolesList = res.data;
      this.setRolesDialogVisible = true;
    },
    async setRoles() {
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        { rid: this.selectRolesId }
      );
      if (res.meta.status !== 200) return this.$message.error("分配角色失败");
      this.$message.success("分配角色成功");
      this.getUserList();
      this.selectRolesId = "";
      this.setRolesDialogVisible = false;
    }
  }
};
</script>

<style lang="less" scoped>
</style>